//
//  ViewController.swift
//  RxObjectDemo
//
//  Created by CaryaLiu on 2021/2/22.
//

import RxSwift
import UIKit

class ViewController: UIViewController {
    private var clLocationManager = CLLocationManager()
    private var locationManager: BMKLocationManager = {
        let locationManager = BMKLocationManager()
        locationManager.distanceFilter = kCLDistanceFilterNone
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.pausesLocationUpdatesAutomatically = true
        locationManager.locationTimeout = 10
        locationManager.reGeocodeTimeout = 10
        locationManager.coordinateType = .GCJ02
        return locationManager
    }()
    let disposeBag = DisposeBag()
    @IBOutlet weak var changeBtn: UIButton!
    @IBOutlet weak var showLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        clLocationManager.desiredAccuracy = kCLLocationAccuracyBest
        clLocationManager.requestAlwaysAuthorization()
        
        locationManager.startUpdatingHeading()
        locationManager.startUpdatingLocation()
        locationManager.rx
            .didChangeAuthorization
            .subscribe(onNext: { event in
                let status = event.status
                print("status: \(status.rawValue)")
            }).disposed(by: disposeBag)
        
        locationManager.rx.didUpdateLocation.subscribe(onNext: { (event) in
            let location = event.location
            print("location: \(location?.location?.description ?? "")")
        }).disposed(by: disposeBag)

        locationManager.rx.doRequestAlwaysAuthorization.subscribe(onNext: { (event) in
            event.locationManager.requestAlwaysAuthorization()
        }).disposed(by: disposeBag)

        locationManager.rx.didUpdateHeading.subscribe(onNext: { (event) in
            if let heading = event.heading {
                print("new heading: \(heading)")
            }
        }).disposed(by: disposeBag)

        locationManager.rx.didUpdateNetworkState.subscribe(onNext: { (event) in
            print("event networkstate: \(event.state)")
        }).disposed(by: disposeBag)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }

    @IBAction func nextBtnTouched(_ sender: Any) {
        if let url = URL(string: UIApplication.openSettingsURLString),
           UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
    }
}
